const currentIndex = localStorage.getItem('currentIndex');
let addressIdList = [];
let totals = 0;
//渲染订单详情
function renderOrderList() {
	ajax({
		method: "POST",
		url: BASE_URL + "/api_settlement",
		type: "JSON",
		params: "userId=" + userId + "&status=getsettlement",
		callback: function(data) {
			console.log(data)
			let text = '';
			let list = data.data;
			let orderList = document.querySelector("#orderList");
			let totalList = document.querySelector("#price");
			list.forEach(item => {
				totals += item.goods_number * item.price;
				text += "<li>" +
					"<div class='orderImg'>" +
					"<img src='" + item.goods_thumb + "'>" +
					"</div>" +
					"<div class='orderInfo'>" +
					"<span style='width:590px;'>" + item.goods_name + "</span>" +
					"<span style='width:60px;'>" + item.goods_number + "</span>" +
					"<span style='width:80px;'>" + item.price + "</span>" +
					"</div>"
				"</li>"
			})
			totalList.innerHTML = totals.toFixed(2);
			orderList.innerHTML = text;
		}
	})
}

//渲染收货地址
function renderAddress(resolve) {
	ajax({
		method: "POST",
		url: BASE_URL + "/api_address",
		type: "JSON",
		params: "userId=" + userId + "&status=getAddress",
		callback: function(data) {
			console.log(data)
			let text = '';
			addressIdList = [];
			let addList = document.querySelector("#addList");
			data.data.forEach((item, index) => {
				if (item.address_id) {
					addressIdList.push(item.address_id);
					text += "<li onclick='setCurrentAdd(" + index + ")'>" +
						"<div class='add_title'>" +
						"<span class='a'>" + item.takename + "</span>" +
						"<span class='b'>" + item.tel + "</span>" +
						"</div>" +
						"<div class='add_content'>" +
						"<p>" + item.province + item.city + item.district + "</p>" +
						"<p>" + item.streetname + "</p>" +
						"</div>" +
						"<div class='add_option'>" +
						"<div class='default'>" +
						"<a href='#' onclick='setDefaultAdd(" + index + ")'>设为默认</a>" +
						"</div>" +
						"<div class='option'>" +
						"<a href='#'>编辑</a>" +
						"<a href='#' onclick='delAddress(" + index + ")'>删除</a>" +
						"</div>" +
						"</div>" +
						"</li>"
				}
			})
			console.log(addressIdList)
			addList.innerHTML = text;
			resolve();
		}
	})
}

//删除用户地址
function delAddress(index) {
	ajax({
		method: "POST",
		url: BASE_URL + "/api_address",
		type: "JSON",
		params: "userId=" + userId + "&addressId=" + addressIdList[index] + "&status=deleteAddress",
		callback: function(data) {
			if(index < currentIndex){
				new Promise((resolve, reject) => {
					renderAddress(resolve);
				}).then((value) => {
					setDefaultAdd(parseInt(currentIndex)-1);
					setCurrentAdd(parseInt(currentIndex)-1);
				})
			}
			else{
				new Promise((resolve, reject) => {
					renderAddress(resolve);
				}).then((value) => {
					setDefaultAdd(currentIndex);
					setCurrentAdd(currentIndex);
				})
			}
		}
	})
}

//设置默认地址
function setDefaultAdd(currentIndex) {
	ajax({
		method: "POST",
		url: BASE_URL + "/api_address",
		type: "JSON",
		params: "userId=" + userId + "&addressId=" + addressIdList[currentIndex] + "&status=defaultAddress",
		callback: function(data) {
			console.log(data)
			localStorage.setItem('currentIndex', currentIndex);
			let default1 = document.querySelectorAll(".default>a");
			data.data.forEach((item, index) => {
				if(item._id){
					if (item.isDefault == true) {
						default1[index].innerHTML = "默认地址";
						default1[index].style.color = "#7fa6c5";
					}
					if (item.isDefault == false) {
						default1[index].innerHTML = "设为默认";
						default1[index].style.color = "#999";
					};
				}
			})
		}
	})
}

// 当前收货地址
function setCurrentAdd(currentIndex) {
	ajax({
		method: "POST",
		url: BASE_URL + "/api_address",
		type: "JSON",
		params: "userId=" + userId + "&addressId=" + addressIdList[currentIndex] + "&status=activeAddress",
		callback: function(data) {
			console.log(data.data);
			let addOption = document.querySelectorAll(".add_option");
			let addList = document.querySelectorAll("#addList>li");
			data.data.forEach((item, index) => {
				if(item._id){
					if (item.isActive == true) {
						addOption[index].style.display = "block";
						addList[index].style.border = "2px solid #7fa6c5";
					};
					if(item.isActive == false) {
						addOption[index].style.display = "none";
						addList[index].style.border = "2px solid #ededed";
					};
				}
			})
		}
	})
}

//渲染省份
function renderProvince() {
	ajax({
		method: "GET",
		url: BASE_URL + "/api_country",
		type: "JSON",
		callback: function(data) {
			let text = "";
			let province = document.querySelector("#province");
			data.data.forEach(item => {
				text += "<option value='" + item.name + "'>" + item.name + "</option>";
			})
			province.innerHTML += text;
		}
	})
}


window.onload = function() {
	renderOrderList();
	renderProvince();
	let province = document.getElementById('province');
	let city = document.getElementById('city');
	let district = document.getElementById('district');
	let newAdd = document.querySelector("#newAdd");
	let add = document.querySelector("#add");
	new Promise((resolve, reject) => {
		renderAddress(resolve);
	}).then((value) => {
		setDefaultAdd(currentIndex);
		setCurrentAdd(currentIndex);
	})
	//添加监听根据省份渲染市区
	province.addEventListener("change", () => {
		ajax({
			method: "GET",
			url: BASE_URL + "/api_country?province=" + province.value,
			type: "JSON",
			callback: function(data) {
				let text = "";
				data.data.forEach(item => {
					text += "<option value='" + item.name + "'>" + item.name +
						"</option>";
				})
				city.innerHTML += text;
			}
		})
	})
	//添加监听根据省份和市区渲染区县
	city.addEventListener("change", () => {
		ajax({
			method: "GET",
			url: BASE_URL + "/api_country?province=" + province.value + "&city=" + city.value,
			type: "JSON",
			callback: function(data) {
				let list = data.data.area;
				let text = "";
				list.forEach(item => {
					text += "<option value='" + item.name + "'>" + item.name +
						"</option>";
				})
				district.innerHTML += text;
			}
		})
	})

	//新增用户地址
	let addBtn = document.querySelector("input[class='addBtn']");
	addBtn.addEventListener("click", () => {
		let name = document.querySelector("#name").value;
		let phone = document.querySelector("#phoneNum").value;
		let address = document.querySelector("#address").value;
		let addForm = document.querySelector("#addForm");
		ajax({
			method: "POST",
			url: BASE_URL + "/api_address",
			type: "JSON",
			params: "userId=" + userId + "&province=" + province.value + "&city=" + city.value +
				"&district=" + district.value + "&streetname=" + address + "&takename=" + name +
				"&tel=" + phone + "&status=addAddress",
			callback: function(data) {
				newAdd.checked = false;
				add.style.display = "none";
				addForm.reset();
				new Promise((resolve, reject) => {
					renderAddress(resolve);
				}).then((value) => {
					setDefaultAdd(parseInt(currentIndex)+1);
					setCurrentAdd(parseInt(currentIndex)+1);
				})
			}
		})
	})

	//添加监听控制新增地址的展示
	newAdd.addEventListener("change", () => {
		if (newAdd.checked) {
			add.style.display = "block";
		} else {
			add.style.display = "none";
		}
	})
	
	//滑动地址页
	let addIndex = 0;
	let addList = document.querySelector("#addList");
	document.querySelector("#pre").addEventListener('click',()=>{
		if(addIndex > 0){
			--addIndex;
			addList.style.transform = `translateX(-${addIndex * 100}%)`;
		}
		else{
			alert("已经到最前面了！");
		}
	})
    document.querySelector("#next").addEventListener('click',()=>{
		console.log(addIndex)
		let li = document.querySelectorAll("#addList>li");
		let maxIndex = parseInt(li.length / 4);
		console.log(maxIndex);
		if(addIndex < maxIndex){
			++addIndex;
			addList.style.transform = `translateX(-${addIndex * 100}%)`;
		}
		else{
			addIndex = 0;
			addList.style.transform = `translateX(-${addIndex * 100}%)`;
		}
	})
	//结算
	document.querySelector("#settle").addEventListener("click", () => {
		//生成当前年月日
		const date = new Date();
		const year = date.getFullYear(); // 2023（年）
		const month = date.getMonth() + 1; // 0-11 → 1-12（需 +1）
		const day = date.getDate(); // 1-31（日）
		const hours = date.getHours(); // 时（0-23）
		const minutes = date.getMinutes(); // 分（0-59）
		const seconds = date.getSeconds(); // 秒（0-59）
		let orderId = year + month + day + hours + minutes + seconds;
		ajax({
			method: "POST",
			type: "JSON",
			url: BASE_URL + "/api_payment",
			params: "userId=" + userId + "&orderId=" + orderId + "&returnUrl=http://127.0.0.1:8848/%E9%A1%B9%E7%9B%AE/order.html?orderId=" + orderId + "&totalAmount=" + totals + "&subject=biaoti5" + "&body=biao6",
			callback: function(data) {
				window.location.href = data.data;
			}
		})
	})

}